package com.kantboot.user.third.party.domain.service.impl;

import com.kantboot.user.account.domain.entity.UserAccount;
import com.kantboot.user.account.domain.vo.LoginVO;
import com.kantboot.user.account.service.IUserAccountService;
import com.kantboot.user.account.service.IUserAccountTokenService;
import com.kantboot.user.third.party.domain.dto.ThirdPartyDTO;
import com.kantboot.user.third.party.domain.entity.UserAccountThirdParty;
import com.kantboot.user.third.party.domain.repository.UserAccountThirdPartyRepository;
import com.kantboot.user.third.party.domain.service.IUserAccountThirdPartyService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class UserAccountThirdPartyServiceImpl implements IUserAccountThirdPartyService {

    @Resource
    private UserAccountThirdPartyRepository repository;

    @Resource
    private IUserAccountTokenService userAccountTokenService;

    @Resource
    private IUserAccountService userAccountService;


    @Override
    public LoginVO login(ThirdPartyDTO thirdPartyDTO) {
        UserAccountThirdParty find = repository.find(thirdPartyDTO);
        if (find == null) {
            // 创建用户
            UserAccount userAccount = userAccountService.createUserAccount(new UserAccount());
            UserAccountThirdParty userAccountThirdParty = new UserAccountThirdParty();
            userAccountThirdParty.setThirdPartyCode(thirdPartyDTO.getThirdPartyCode());
            userAccountThirdParty.setKey(thirdPartyDTO.getKey());
            userAccountThirdParty.setValue(thirdPartyDTO.getValue());
            userAccountThirdParty.setUserAccountId(userAccount.getId());
            find = repository.save(userAccountThirdParty);
        }
        // 生成令牌
        String token = userAccountTokenService.generateToken(find.getId());
        UserAccount userAccount = userAccountService.getById(find.getUserAccountId());
        return new LoginVO()
                .setToken(token)
                .setUserAccount(userAccount);
    }
}
